package com.zsyh.jiujiu.conference.chat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;


import com.google.common.eventbus.Subscribe;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.EaseChatInputMenu;
import com.hyphenate.easeui.widget.EaseChatPrimaryMenu;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.exceptions.HyphenateException;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zsyh.jiujiu.R;
import com.zsyh.jiujiu.bean.ChangYongMsgBean;

import java.io.File;
import java.util.List;

import io.reactivex.Maybe;
import io.reactivex.MaybeEmitter;
import io.reactivex.MaybeOnSubscribe;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MyChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentHelper, EaseChatInputMenu.ToggleVoiceBtnClicked {


    private Observable<Boolean> observable;


    @Override
    public void onAvatarClick(String username) {

    }

    @Override
    protected void initView() {
        //RxBusUtil.register(this);

        //预加载本地聊天记录
        int pagesize = 20;
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(1), true);

        final List<EMMessage> msgs = conversation.getAllMessages();
        if(null!=msgs){
            int msgCount = msgs != null ? msgs.size() : 0;
            if (msgCount > 0) {
                String msgId = msgs.get(msgCount - 1).getMsgId();
                //LogUtil.d(TAG, "msg0:" + msgs.get(msgCount - 1).toString());
                conversation.loadMoreMsgFromDB(msgId, conversation.getAllMsgCount());
            }
        }



        isRoaming = true;
        super.initView();
        setChatFragmentHelper(this);
        RxPermissions rxPermissions = new RxPermissions(this);
        observable = rxPermissions.request(Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    @Override
    public void onDestroy() {
        //RxBusUtil.unRegister(this);
        super.onDestroy();
    }

    @Subscribe
    public void sendChangyongyu(ChangYongMsgBean bean){
        inputMenu.insertText(bean.getContent());


//        sendTextMessage(bean.getContent());
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        titleBar.getRightLayout().setVisibility(View.INVISIBLE);
        //inputMenu.setToggleVoiceBtnClickedListener(this);
    }

    @Override
    protected void registerExtendMenuItem() {
        super.registerExtendMenuItem();
       // inputMenu.registerExtendMenuItem("常用语", R.drawable.ic_changyongyu, 4, extendMenuItemClickListener);
    }

    @Override
    public void onSetMessageAttributes(EMMessage message) {
        if (message.direct() == EMMessage.Direct.SEND) {
//            // 设置自定义推送提示(华为角标使用)
//            JSONObject extObject = new JSONObject();
//            try {
//                extObject.put("em_huawei_push_badge_class", "com.zswl.abroadstudent.ui.login.SplashActivity");
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//            // 将推送扩展设置到消息中
//            message.setAttribute("em_apns_ext", extObject);


          /*  message.setAttribute("avatar", SpFastUtil.getHeaderImg());
            message.setAttribute("id", SpFastUtil.getUserId());
            message.setAttribute("userName", SpFastUtil.getNickName());
            message.setAttribute("userType", "1");*/
        }
        hideKeyboard();
    }

    @Override
    public void onEnterToChatDetails() {

    }




    @Override
    public void onAvatarLongClick(String username) {

    }

    @Override
    public boolean onMessageBubbleClick(EMMessage message) {

        return false;
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {
        EMMessageBody body = message.getBody();
        if (body instanceof EMTextMessageBody) {

            //获取剪贴板管理器：
            ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", ((EMTextMessageBody) body).getMessage());
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            //ToastUtil.showShortToast("复制成功");
        } else if (body instanceof EMImageMessageBody) {

            String path = ((EMImageMessageBody) body).getRemoteUrl();
           // LogUtil.d(TAG, "path:" + path);



        }


    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {



        return false;
    }


    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        return null;
    }


    @Override
    protected void selectPicFromLocal() {
        observable.subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    MyChatFragment.super.selectPicFromLocal();
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    @Override
    protected void selectPicFromCamera() {
        observable.subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    MyChatFragment.super.selectPicFromCamera();
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }













    @Override
    public void onToggleVoiceBtnClicked() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.RECORD_AUDIO)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (!aBoolean) {
                           // ToastUtil.showShortToast("请授权相应的权限，否则无法使用此功能");
                            EaseChatPrimaryMenu primaryMenu = (EaseChatPrimaryMenu) inputMenu.getPrimaryMenu();
                            primaryMenu.setModeKeyboard();
                            primaryMenu.showNormalFaceImage();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
}
